import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getDeviceList, getDeviceStats } from '@/api/device'

export const useDeviceStore = defineStore('device', () => {
  // 状态
  const devices = ref([])
  const stats = ref({
    total: 0,
    online: 0,
    offline: 0,
    onlineRate: 0
  })
  const loading = ref(false)

  // 计算属性
  const onlineDevices = computed(() => {
    return devices.value.filter(d => d.status === 'online')
  })

  const offlineDevices = computed(() => {
    return devices.value.filter(d => d.status === 'offline')
  })

  // 方法
  async function fetchDevices(params) {
    loading.value = true
    try {
      const res = await getDeviceList(params)
      devices.value = res.data.list
      return res.data
    } catch (error) {
      console.error('获取设备列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  async function fetchStats() {
    try {
      const res = await getDeviceStats()
      stats.value = res.data
      return res.data
    } catch (error) {
      console.error('获取统计信息失败:', error)
      throw error
    }
  }

  function clearDevices() {
    devices.value = []
  }

  return {
    devices,
    stats,
    loading,
    onlineDevices,
    offlineDevices,
    fetchDevices,
    fetchStats,
    clearDevices
  }
})

